package com.benefm.multipar.pad.dashboard;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Intent;
import android.hardware.SensorManager;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.text.TextUtils;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;

import com.benefm.multipar.pad.BaseApp;
import com.benefm.multipar.pad.MqttManager;
import com.benefm.multipar.pad.R;
import com.benefm.multipar.pad.ble.BLEManager;
import com.benefm.multipar.pad.databinding.ActivityDashboardBinding;
import com.benefm.multipar.pad.event.AtmosphericPressure;
import com.benefm.multipar.pad.event.CarbonDioxideEvent;
import com.benefm.multipar.pad.event.EventAction;
import com.benefm.multipar.pad.event.GyroscopeInfoEvent;
import com.benefm.multipar.pad.event.HrBatteryEvent;
import com.benefm.multipar.pad.event.LatLngEvent;
import com.benefm.multipar.pad.event.MsgEvent;
import com.benefm.multipar.pad.model.PersonInfo;
import com.benefm.multipar.pad.view.EcgWaveData;
import com.bumptech.glide.Glide;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Vector;

public class DashboardActivity extends AppCompatActivity {

    private ActivityDashboardBinding binding;

    private Vector<Integer> hrArray = new Vector<>();
    private Integer count = 0;

    public static final int N = 125;
    private float[] hfDataI = new float[N];
    private int hfPtrI = 0;
    private float hfyI = 0;
    private String userId;
    private int locationCount = 0;
    private PersonInfo info;
    private MqttManager manager;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_dashboard);

        EventBus.getDefault().register(this);

        Glide.with(this)
                .asGif()
                .load(R.mipmap.clothing)
                .thumbnail(0.25f)
                .into(binding.clothing);

        //113.951759,22.516268
        //113.945800,22.515200 科苑南路
//        getAddressFromLocation(22.515200, 113.945800);

        if (getIntent().hasExtra("info")) {
            info = (PersonInfo) getIntent().getSerializableExtra("info");
            userId = info.userId;
            manager = new MqttManager(info.deviceMac);
            manager.initMqtt();
        }

        addListener();

    }

    private void addListener() {

        binding.topImage.setOnClickListener(v -> startActivity(new Intent(DashboardActivity.this, OnlineDeviceActivity.class)));

        binding.ecgLayout.setOnClickListener(v -> {
            Intent intent = new Intent(this, EcgLead12Activity.class);
            if (!TextUtils.isEmpty(userId))
                intent.putExtra("userId", userId);
            startActivity(intent);
        });
    }


    @SuppressLint({"DefaultLocale", "SetTextI18n"})
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMsgEvent(MsgEvent event) {
        String userId = event.getTag();
        if (!TextUtils.isEmpty(userId) && !this.userId.equalsIgnoreCase(userId)) {
            return;
        }
        if (event.getAction() == EventAction.DEVICE_SPO2) {//血氧
            int spo2 = (int) event.getT();
            binding.textSpo2.setText(String.valueOf(spo2));

        } else if (event.getAction() == EventAction.DEVICE_SPO2_INVALID) {//血氧无效
            binding.textSpo2.setText("--");

        } else if (EventAction.DEVICE_TEMPERATURE == event.getAction()) {//温度值
            int temp = (int) event.getT();
            binding.textTemp.setText(String.format("%.1f", temp / 100f));
        } else if (EventAction.DEVICE_TEMPERATURE_INVALID == event.getAction()) {
            binding.textTemp.setText("--");

        } else if (EventAction.DEVICE_TEMPERATURE_HUMIDITY == event.getAction()) {//二氧化碳温湿度
            CarbonDioxideEvent dioxide = (CarbonDioxideEvent) event.getT();
            boolean co2Invalid = dioxide.value == 0 || dioxide.value == 0xffff;
            binding.textCarbonDioxide.setText(co2Invalid ? "--" : String.valueOf(dioxide.value));

            boolean tempInvalid = dioxide.temp == 0 || dioxide.temp == 0x8000;
            boolean humidityInvalid = dioxide.humidity == 0 || dioxide.temp == 0xffff;

            binding.innerTempHumidity.setText((tempInvalid ? "--" : String.format("%.1f", dioxide.temp / 10f)) + " / " +
                    (humidityInvalid ? "--" : dioxide.humidity));

        } else if (EventAction.DEVICE_ATMOSPHERIC_PRESSURE == event.getAction()) {//大气压强
            AtmosphericPressure ap = (AtmosphericPressure) event.getT();
            binding.textAtmospheric.setText(ap.value == 0xffff ? "--" : String.format("%.2f", ap.value / 100f));
            binding.outsideTempHumidity.setText((ap.temp == 0x8000 ? "--" : String.format("%.1f", ap.temp / 10f)) + " / "
                    + (ap.humidity == 0xffff ? "--" : ap.humidity));

            //根据大气压强计算海拔 这里传递的是hKp
            if (ap.value != 0xffff) {
                float altitude = SensorManager.getAltitude(SensorManager.PRESSURE_STANDARD_ATMOSPHERE, ap.value / 10f);
                binding.textAltitude.setText(String.valueOf((int) altitude));
            }
        } else if (EventAction.DEVICE_GYROSCOPE == event.getAction()) {//陀螺仪数据
            GyroscopeInfoEvent infoEvent = (GyroscopeInfoEvent) event.getT();
            if (infoEvent.degrees > 70.0)
                binding.imageAttitude.setImageResource(R.mipmap.icon_fall);
            else
                binding.imageAttitude.setImageResource(R.mipmap.icon_stand);

        } else if (EventAction.DEVICE_ECG_HR == event.getAction()) {//心率
            int hr = (int) event.getT();
            if (hr < 30 || hr > 300) {
                binding.textHr.setText("NA");
            } else {
                if (hrArray.size() == 6) {
                    Collections.sort(hrArray);
                    int mHr = (hrArray.get(2) + hrArray.get(3)) / 2;
                    binding.textHr.setText(String.valueOf(mHr));
                    binding.textRespire.setText(String.valueOf(mHr / 4));
                    hrArray.set(count, hr);
                    count++;
                    if (count == 6) count = 0;
                } else if (hrArray.size() < 6) {
                    hrArray.add(hr);
                }
            }
//            binding.textHr.setText(String.valueOf(hr));
//            binding.textRespire.setText(String.valueOf(hr / 4));
        } else if (EventAction.ECG_HR_BATTERY == event.getAction()) {
            HrBatteryEvent model = (HrBatteryEvent) event.getT();
            if (model.hr < 30 || model.hr > 300) {
                binding.textHr.setText("NA");
            } else {
                if (hrArray.size() == 6) {
                    Collections.sort(hrArray);
                    int mHr = (hrArray.get(2) + hrArray.get(3)) / 2;
                    binding.textHr.setText(String.valueOf(mHr));
                    binding.textRespire.setText(String.valueOf(mHr / 4));
                    hrArray.set(count, model.hr);
                    count++;
                    if (count == 6) count = 0;
                } else if (hrArray.size() < 6) {
                    hrArray.add(model.hr);
                }
            }
        } else if (EventAction.DEVICE_RESP_DATA == event.getAction()) {//呼吸
//            int resp = (int) event.getT();
//            binding.textRespire.setText(String.valueOf(resp));

        } else if (EventAction.DEVICE_LATITUDE_LONGITUDE == event.getAction()) {//经纬度
            //经纬度 = N0.0000000,E0.0000000
            LatLngEvent latlng = (LatLngEvent) event.getT();
            if (TextUtils.isEmpty(latlng.lat) || TextUtils.isEmpty(latlng.lng))
                return;
            locationCount++;
            if (locationCount == 1 || locationCount % 5 == 0) {
                double lat = Double.parseDouble(latlng.lat.replace("N", ""));
                double lng = Double.parseDouble(latlng.lng.replace("E", ""));
                getAddressFromLocation(lat, lng);
            }
        } else if (EventAction.ECG_DATA_LEAD_II == event.getAction()) {
            ArrayList<EcgWaveData> data = new ArrayList<>();
            List<Short> list = (List<Short>) event.getT();
            for (short f : list) {
                data.add(new EcgWaveData(1, convertData(f)));
            }
            binding.ecgView.notifyData(data);
        } else if (EventAction.DEVICE_DISCONNECTED == event.getAction()) {
            new AlertDialog.Builder(this)
                    .setMessage("设备连接已断开，请检查！")
                    .setPositiveButton("知道了", (dialog, which) -> {
                        dialog.dismiss();
                    })
                    .create()
                    .show();
        }

    }

    public float convertData(Short data) {
        hfyI = hfyI + Float.parseFloat(String.valueOf(data)) - hfDataI[hfPtrI];
        int halfPtr = hfPtrI - N / 2;
        if (halfPtr < 0)
            halfPtr = halfPtr + N;
        float out = hfDataI[halfPtr] - (hfyI / N);
        hfDataI[hfPtrI] = data;
        hfPtrI = hfPtrI + 1;
        if (hfPtrI == N) {
            hfPtrI = 0;
        }
        return out;
    }

    private void getAddressFromLocation(double latitude, double longitude) {
        if (BaseApp.isDebug)
            System.out.println("开始获取位置信息，经纬度为" + latitude + "," + longitude);
        Geocoder geocoder = new Geocoder(this, Locale.getDefault());
        List<Address> addresses;
        try {
            addresses = geocoder.getFromLocation(latitude, longitude, 1);
            if (addresses != null && !addresses.isEmpty()) {
                Address address = addresses.get(0);
                System.out.println(address.getAddressLine(0));
                binding.textAddress.setText(address.getAddressLine(0));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (manager != null) {
            manager.unsubscribeTopic();
            manager.disconnect();
        }
        BLEManager.getInstance().disconnect();
        EventBus.getDefault().unregister(this);
    }
}
